﻿using System;
using System.Collections.Generic;

namespace com.uplus.common
{
    public class PostDataMgr
    {
        private Dictionary<string, string> postValues;

        public PostDataMgr(string postDataString)
        {
            postValues = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(postDataString))
            {
                foreach (string item in postDataString.Split('&'))
                {
                    string key = item.Substring(0, item.IndexOf('=')).Trim();
                    string value = item.Substring(item.IndexOf('=') + 1).Trim('{', '}');
                    postValues.Add(key, value);
                }
            }
        }

        public string this[string key]
        {
            get
            {
                return postValues.ContainsKey(key) ? postValues[key] : string.Empty;
            }
        }

        public T To<T>(string key, T defaultValue)
        {
            if (postValues != null && postValues.ContainsKey(key))
            {
                try
                {
                    object re = Convert.ChangeType(postValues[key], typeof(T));
                    return (T)re;
                }
                catch { }
            }
            return defaultValue;
        }
    }
}
